contextPath = contextPath || ''

layui.use(['table', 'jquery'], function () {
    var table = layui.table,
        $ = layui.jquery,
        layer = layui.layer,
        form = layui.form;

    // 自定义验证规则
    form.verify({
        code: function(value, item) {
            if(!/^[A-Z]{2,10}$/.test(value)) {
                return '编码必须是2-10位大写字母';
            }
        }
    });

    var tableRen = table.render({
        elem: '#bookTypeTable',
        url: contextPath + '/bookType/list',
        page: true,
        toolbar: "#toolbar",
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'name', title: '名称', width: 200},
            {field: 'code', title: '编码', width: 120, align: 'center'},
            {field: 'remark', title: '备注'},
            {title: "操作", fixed: 'right', width: 220, align: "center", toolbar: "#operation"}
        ]]
    });

    table.on("tool(bookTypeTable)", function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent == "bookTypeUpdate") {
            $("#bookTypeUpdateForm form")[0].reset();
            //给表单赋初值
            form.val("bookTypeUpdateForm", data);
            layer.open({
                type: 1,
                title: "修改分类信息",
                area: ['450px', '420px'],
                content: $("#bookTypeUpdateForm"),
                btn: ["提交", "重置", "取消"],
                success: function (layero) {
                    layero.addClass('layui-form');
                    layero.find('.layui-layer-btn0').attr({
                        'lay-filter': 'formSubmit',
                        'lay-submit': '',
                        'id': 'submitBtn'
                    });
                },
                yes: function () {
                    form.render();
                },
                btn2: function () {
                    $("#bookTypeUpdateForm form")[0].reset();
                    // 重新赋值
                    form.val("bookTypeUpdateForm", data);
                    return false;
                },
                btnAlign: "c"
            });
        } else if (layEvent == 'bookTypeDelete') {
            layer.confirm("是否删除当前分类（" + data.name + "）?", {
                icon: 3,
                title: '提示'
            }, function () {
                formByAjax("bookType/delete?bookTypeIds=" + [data.bookTypeId], null, "删除", "close");
            });
        }
    });

    table.on('toolbar(bookTypeTable)', function (obj) {
        var checks = table.checkStatus("bookTypeTable").data;
        var ids = checks.map(check => check.bookTypeId);
        var layEvent = obj.event;
        var len = checks.length;
        if (len == 0 && layEvent != "bookTypeAdd" && layEvent != "search" && layEvent != "reset") {
            layer.msg("请至少选中一个分类");
            return;
        }

        if (layEvent == "bookTypeAdd") {
            $("#bookTypeUpdateForm form")[0].reset();
            layer.open({
                type: 1,
                title: "添加分类",
                area: ['450px', '420px'],
                content: $("#bookTypeUpdateForm"),
                btn: ["提交", "重置", "取消"],
                success: function (layero) {
                    layero.addClass('layui-form');
                    layero.find('.layui-layer-btn0').attr({
                        'lay-filter': 'formSubmit',
                        'lay-submit': '',
                        'id': 'submitBtn'
                    });
                },
                yes: function () {
                    form.render();
                },
                btn2: function () {
                    $("#bookTypeUpdateForm form")[0].reset();
                    return false;
                },
                btnAlign: "c"
            });
        } else if (layEvent == 'search') {
            var params = $("#searchForm form").serialize();
            tableRen.reload({
                url: contextPath + '/bookType/list' + jsonToUrlParams(formToJson(params))
            });
        } else if (layEvent == 'reset') {
            $("#searchForm form")[0].reset();
            tableRen.reload({
                url: contextPath + '/bookType/list'
            });
        } else if (layEvent == 'bookTypeDeletes') {
            layer.confirm("是否删除选中的" + len + "个分类?", {
                icon: 3,
                title: '提示'
            }, function () {
                formByAjax("bookType/delete?bookTypeIds=" + ids, null, "删除", "close");
            });
        }
    });

    //表单提交
    form.on("submit(formSubmit)", function (e) {
        var data = e.field;
        // 将编码转为大写
        if (data.code) {
            data.code = data.code.toUpperCase();
        }
        
        if (data.bookTypeId) {
            formByAjax("bookType/update", data, "修改", "close");
        } else {
            formByAjax("bookType/add", data, "添加", "close");
        }
        return false;
    });

    function formByAjax(url, data, tips, close, fun) {
        $.ajax({
            type: 'post',
            url: url,
            data: JSON.stringify(data),
            dataType: 'json',
            contentType: 'application/json',
            success: function (res) {
                if (res.code == 200) {
                    if (fun) {
                        fun.call();
                    }
                    if (close == "close") {
                        layer.closeAll();
                    }
                    table.reload("bookTypeTable");
                    layer.msg(tips + "成功");
                } else {
                    layer.msg(tips + "失败，" + res.msg);
                }
            },
            error: function (res) {
                layer.msg(res.statusText);
            }
        });
    }
});